<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar">
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
        <el-row class="search-input">
          <el-form-item label="品牌名称：">
            <el-input v-model="filters.orgNumber" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item label="商户名称：">
            <el-input v-model="filters.name" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item label="商户code：">
            <el-input v-model="filters.thirdMerchantCode" placeholder=" " clearable></el-input>
          </el-form-item>
          <el-form-item label="申请时间">
            <el-date-picker v-model="filters.aa" type="date" placeholder="选择日期"></el-date-picker>
          </el-form-item>
        </el-row>
        <el-row class="search-button">
          <el-form-item>
            <kt-button
              icon="fa fa-search"
              :label="$t('action.search')"
              type="primary"
              @click="findPage(null)"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-refresh"
              :label="$t('action.reset')"
              type="primary"
              @click="resetForm('filters')"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-plus"
              label="添加品牌"
              type="primary"
              @click="handleAdd"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" @click="reviewStatus">批量提交审核</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" @click="reviewStatus">批量审核</el-button>
          </el-form-item>
        </el-row>
        <el-form-item class="t_r w100">
          <el-button-group>
            <el-tooltip content="刷新" placement="top">
              <el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
            </el-tooltip>
            <el-tooltip content="列显示" placement="top">
              <el-button icon="fa fa-filter" @click="displayFilterColumnsDialog"></el-button>
            </el-tooltip>
          </el-button-group>
        </el-form-item>
      </el-form>
    </div>
    <!--表格内容栏-->
    <div class="tab-container">
      <!-- tbs标签 -->
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane v-for="item in tabMapOptions" :key="item.key" :label="item.label" :name="item.key">
        </el-tab-pane>
      </el-tabs>
      <!-- jic table表格-->
      <div class="toolbar" >
        <!--表格显示列界面-->
        <table-column-filter-dialog
          ref="tableColumnFilterDialog"
          :columns="columns"
          @handleFilterColumns="handleFilterColumns"
        ></table-column-filter-dialog>
      </div>
      <!--表格内容栏-->
      <jic-table
        ref="JicTable"
        :data="pageResult"
        :operationWidth="390"
        :totalSize="totalSize"
        :columns="filterColumns"
        :showCopyDataOperation="true"
        :showCopyLinkOperation="false"
        :showDetailOperation="true"
        :showBatchDelete="false"
        :loading="loading"
        :btnList="btnList"
        @findPage="findPage"
        @handleEdit="handleEdit"
        @handleDetail="handleDetail"
        ></jic-table>
    </div>
    <!--新增编辑界面-->
    <el-dialog title="添加品牌" width="50%" :visible.sync="editDialogVisible" :close-on-click-modal="false" @closed="handleClose">
        <el-form
          :model="dataForm"
          label-width="110px"
          :rules="dataFormRules"
          ref="dataForm"
          :size="size"
        >
          <el-row class="searchDialog-input">


              <el-form-item label="品牌名称：" prop="orgNumber">
                <el-input
                  v-model="dataForm.orgNumber"
                  style="width:50%"
                  auto-complete="off"
                  :disabled="false"
                  placeholder="请输入品牌名称"
                ></el-input>
                <el-autocomplete v-model="state4" :fetch-suggestions="querySearchAsync" placeholder="请输入内容"  @select="handleSelect"></el-autocomplete>
            </el-form-item>


            <el-form-item label="品牌LOGO：" prop="pic">
              <div style="float: left;">
                <ul class="el-upload-list el-upload-list--picture-card">
                  <li
                    v-for="(bill_photo,index) in bill_photo_list"
                    :key="index"
                    :tabindex="index"
                    class="el-upload-list__item is-success"
                  >
                    <img :src="bill_photo" alt class="el-upload-list__item-thumbnail" />
                    <label class="el-upload-list__item-status-label">
                      <i class="el-icon-upload-success el-icon-check"></i>
                    </label>
                    <i class="el-icon-close"></i>
                    <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview">
                          <i class="el-icon-zoom-in" @click="handlePictureCardPreview(null,bill_photo)"></i>
                        </span>
                        <span class="el-upload-list__item-delete">
                          <i class="el-icon-delete" @click="handleRemove(null,null,index)"></i>
                        </span>
                      </span>
                  </li>
                </ul>
              </div>

              <el-upload
                :action="imgUpload"
                :on-success="handleAvatarSuccess"
                list-type="picture-card"
                v-model="dataForm.pic"
                accept="image/gif, image/jpeg, image/jpg, image/png, image/svg"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :limit="1"
                ref="upload"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>


          <el-form-item label="品牌持有人：" prop="name">
            <el-input
              v-model="dataForm.name"
              style="width:50%"
              auto-complete="off"
              :disabled="false"
              placeholder="请输入持有人名称"
            ></el-input>
          </el-form-item>
          <div>
            <p><span>品牌授权信息：</span></p>
            <div style="argin-left: 100px; margin-top: 20px; border: 1px solid #DCDFE6;">


              <el-form-item label="证书有效期：" prop="createTime">
                <el-date-picker
                  v-model="filters.createTime"
                  style="width:20%"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期"
                ></el-date-picker>
                <span>至</span>
                <el-date-picker
                  v-model="filters.createTimes"
                  style="width:20%"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期"
                ></el-date-picker>
              </el-form-item>

              <el-form-item label="品牌授权书：" prop="fileUrl">
                <div style="float: left;">
                  <ul class="el-upload-list el-upload-list--picture-card">
                    <li
                      v-for="(bill_photo,index) in bill_photo_list"
                      :key="index"
                      :tabindex="index"
                      class="el-upload-list__item is-success"
                    >
                      <img :src="bill_photo" alt class="el-upload-list__item-thumbnail" />
                      <label class="el-upload-list__item-status-label">
                        <i class="el-icon-upload-success el-icon-check"></i>
                      </label>
                      <i class="el-icon-close"></i>
                      <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview">
                          <i class="el-icon-zoom-in" @click="handlePictureCardPreview(null,bill_photo)"></i>
                        </span>
                        <span class="el-upload-list__item-delete">
                          <i class="el-icon-delete" @click="handleRemove(null,null,index)"></i>
                        </span>
                      </span>
                    </li>
                  </ul>
                </div>

                <el-upload
                  :action="imgUpload"
                  :on-success="handleAvatarSuccess"
                  list-type="picture-card"
                  v-model="dataForm.fileUrl"
                  accept="image/gif, image/jpeg, image/jpg, image/png, image/svg"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :limit="1"
                  ref="upload"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisibleImage">
                  <img width="100%" :src="dialogImageUrl" alt />
                </el-dialog>
              </el-form-item>
            </div>
          </div>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="editDialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="handleInsert"
          :loading="editLoading"
        >{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { exportExcel } from "@/utils/excel";
import JicTable from "./MerchantTbale";
import KtButton from "@/views/Core/KtButton";
import { format } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import {
  validatePhone,
  validateContacts,
  isEmail,
  isNumber
} from "@/utils/validate";

export default {
  components: {
    JicTable,
    KtButton,
    TableColumnFilterDialog
  },
  data() {
    var account = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("账号为必填"));
      } else if (value.length < 1 || value.length > 30) {
        return callback(new Error("账号为1-30字符"));
      } else if (value == " ") {
        return callback(new Error("账号不可为纯空格"));
      } else if (/\s/.test(value)) {
        return callback(new Error("账号不可含有纯空格"));
      } else if (!/^[\u4e00-\u9fa5_a-zA-Z0-9]+$/.test(value)) {
        return callback(new Error("账号不可为纯符号"));
      } else {
        callback();
      }
    };
    return {
      imgUpload: this.utils.imgUploadUrl,//前台类目图片上传
      tabMapOptions: [
        { label: "全部", key: "99" },
        { label: "待提交 0", key: "991" },
        { label: "待审核 0", key: "992" },
        { label: "审核通过 0", key: "993" },
        { label: "审核不通过", key: "994" },
      ],
      activeName: "0",
      //列表按钮
      btnList: [{
          "customLabel": "查看",
          "isShowMethod": "1,2,3,4",
          "method": "handleDetail",
          "perms": "sys:role:add"
      },{
          "customLabel": "编辑",
          "isShowMethod": "1,3,4",
          "method": "handleEdit",
          "perms": "sys:role:add"
      }, {
          "customLabel": "删除",
          "isShowMethod": "1,3,4",
          "method": "deleteLottery",
          "perms": "sys:role:add"
      }, {
          "customLabel": "提交审核",
          "isShowMethod": "1,4",
          "method": "deleteLottery",
          "perms": "sys:role:add"
      }, {
          "customLabel": "审核",
          "isShowMethod": "2",
          "method": "deleteLottery",
          "perms": "sys:role:add"
      }],
      
      totalSize:0,
      
      loading:true,
      content: "",
      size: "small",
      filters: {
        status: '99',
      },
      columns: [
        { prop: "name", label: "商户名称", minWidth: 120 },
        { prop: "thirdMerchantCode", label: "商户code", minWidth: 120 },
        { prop: "merchantType", label: "品牌名称", minWidth: 120,},
        { prop: "merchantType", label: "品牌别名", minWidth: 120,},
        { prop: "merchantType", label: "品牌LOGO", minWidth: 120,},
        { prop: "merchantType", label: "品牌授权证书/证书有效期", minWidth: 160,},
        { prop: "merchantType", label: "申请时间", minWidth: 120,},
        {
          prop: "status",
          label: "审核状态",
          minWidth: 120,
          formatter: this.statusFormatter
        },
      ],
      filterColumns: [],
      pageRequest: { pageNum: 1, pageSize: 10 },
      pageResult: {},

      dataFormRules: {
        orgNumber: [
          { required: true, message: "请输入商户编码", trigger: "blur" }
        ],
        name: [
          { required: true, validator: validateContacts, trigger: "blur" }
        ],
        merchantType: [
          { required: true, message: "请选择商户类型", trigger: "change" }
        ],
        // deptId: [
        //   { required: true, message: "请选择所属组织", trigger: "change" }
        // ],
        roleId: [
          { required: true, message: "请选择账号角色", trigger: "change" }
        ],
        account: [{ required: true, validator: account, trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        contactName: [
          { required: true, validator: validateContacts, trigger: "blur" }
        ],
        contactMobile: [
          { required: true, validator: validatePhone, trigger: "blur" }
        ]
      },

      operation: false, // true:新增, false:编辑
      editDialogVisible: false, // 新增编辑界面是否显示
      dialogVisibleImage: false,
      dialogImageUrl: "",
      bill_photo_list:[],
      editLoading: false,
      // 新增编辑界面数据
      dataForm: {
        orgNumber: "",
        name: "",
        merchantType: "",
        // account: "",
        // password: "",
        // roleId: "",
        // deptId: "",
        contactName: "",
        contactMobile: ""
      },
      checked: [],
      shopList: [],
      statusList: [],
      deptList: [], //部门列表
      roleList: []
    };
  },
  
  watch: {
    activeName(val) {
      if(val != '0'){
        this.filters.status = val;
      }else{
        this.filters.status = null;
      }
      this.findPage();
    }

  },
  created() {
    // init the default selected tab
    const tab = this.$route.query.tab
    if (tab) {
      this.activeName = tab
    }
  },
  methods: {
    // 获取分页数据
    findPage: function(data) {
      if (data != null && data.start != null) {
        if (data.start != null) {
          this.pageRequest.pageNum = data.start;
        }
        if (data.limit != null) {
          this.pageRequest.pageSize = data.limit;
        }
      }
      let this_ = this;
      if (this_.filters == undefined || this_.filters == null) {
        this_.filters = {};
      }
      this_.filters.start = this.pageRequest.pageNum;
      this_.filters.limit = this.pageRequest.pageSize;
      this.utils.request.queryMerchantWeBankBrand(this_.filters, function(res) {
        if (res.data == null) {
          this_.loading = false;
          res.data = [];
          res.totle = 0;
        } else {
          this_.loading = false;
          this_.$refs.JicTable.findPage({
            content: res.data.rows,
            total: res.data.total
          });
        }
      });
    },

    loadAll() {
      return [
        { "value": "三全鲜食（北新泾店）" },
        { "value": "Hot honey 首尔炸鸡（仙霞路）"},
        { "value": "新旺角茶餐厅",  },
        { "value": "泷千家(天山西路店)"},
      ];
    },
    querySearchAsync(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 3000 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      console.log(item);
    },
    
   // 处理图片卡预览
    handlePictureCardPreview(res, file) {
      this.dialogImageUrl = file;
      this.dialogVisibleImage = true;
    },
    //上传成功回调
    handleAvatarSuccess(res, file) {
      var this_=this
      let url = res.data.imgUrl;
      if (res.data.imgUrl == "") {
        this_.$message({ message: "上传失败", type: "error" });
      } else {
        this_.fileUrl += url + ",";
        this.imageUrl = URL.createObjectURL(file.raw);
      }
    },
    // 图片移除
    handleRemove(file, fileList, index) {
      if (this.utils.isNull(index)) {
        this.fileList = fileList;
        if (fileList.length == 0) {
          this.fileUrl = "";
        } else {
          this.imgs = fileList
            .map(item => item.response.data.imgUrl)
            .toString();
          this.fileUrl = this.imgs;
        }
      } else {
        this.bill_photo_list.splice(index, 1);
      }
    },
    //获取选择框数据
    selectionChange(val) {
      this.checked = val.selections;
    },
    // 显示新增界面
    handleAdd: function() {
      this.editDialogVisible = true;
      this.operation = true;
      this.resetForm("dataForm");
    },
    // 显示批量审核弹窗
    reviewStatus: function() {
      if (this.checked.length < 1) {
        this.$message({ message: "必须选中一条数据", type: "warning" });
        return false;
      }
      console.log(this.checked);
      this.reviewFormVisible = true;
      //this.resetForm("reviewForm");
    },
    handleClose() {
      (this.dataForm = {
        orgNumber: "",
        name: "",
        merchantType: "",
        account: "",
        password: "",
        contactName: "",
        contactMobile: ""
      }),
        this.$refs.dataForm.resetFields();
    },
    // 审核通过
    reviewSuccess() {
      
    },
    // 编辑页面
    handleEdit: function(data) {
      
    },
    // 详情页面
    handleDetail: function(data) {
      
    },
    //新增商户品牌信息
    handleInsert: function() {
        this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            let params = Object.assign({}, this.dataForm);
            params.status = 2;
            var this_ = this;
            this.utils.request.insertMerchantWeBankBrand(params, function(res) {
              if (res.code == "0000") {
                this_.$message({ message: "操作成功", type: "success" });

                this_.$refs["dataForm"].resetFields();

                this_.editDialogVisible = false;

                this_.findPage(null);
              } else {
                this_.$message({
                  message: "操作失败, " + res.msg,
                  type: "error"
                });
              }
            });
          });
        }
      });
    },
    // 编辑
    submitForm: function() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            let params = Object.assign({}, this.dataForm);
            
          });
        }
      });
    },

    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },

    resetForm(formName) {
      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
        this.filters = {};
        this.findPage(null);
      }
    },

    // 处理表格列过滤显示
    displayFilterColumnsDialog: function() {
      this.$refs.tableColumnFilterDialog.setDialogVisible(true);
    },
    // 处理表格列过滤显示
    handleFilterColumns: function(data) {
      this.filterColumns = data.filterColumns;
      this.$refs.tableColumnFilterDialog.setDialogVisible(false);
    },
    // 处理表格列过滤显示
    initColumns: function() {
      var temp = [];

      $.each(this.columns, function(key, val) {
        temp.push(val);
      });
      this.filterColumns = temp;
    },
  },
  mounted() {
    this.initColumns();
    this.findPage();
    this.restaurants = this.loadAll();
  }
};
</script>

<style lang="scss" scoped>
</style>
